/**
 * Created by John on 2017/9/18.
 */
var https = require('https');

var errorHandler = function (error,callback) {
    console.log(error);
    callback(error);
}

var onRequest = function (request,callback) {
    request.on('response',function (response) {
        var result = [],size=0;
        response.on('data', function (data) {
            result.push(data);
            size += data.length;
        });
        response.on('end', function () {
            callback(null, Buffer.concat(result, size));
        });
        response.on('error', function (e) {
            errorHandler(e, callback);
        });
    });
    request.on('error', function (e) {
        errorHandler(e, callback);
    });
}

module.exports = {

    getJSON:function (url,callback) {
        onRequest(https.get(url),function (err,data){
            if (data){
                try{
                  data = JSON.parse(data);
                }catch(e){
                    errorHandler(e, callback);
                    return;
                }
            }
            callback(err, data);
        });
    }
}